package durst.action.account;

import java.io.IOException;
import java.sql.SQLException;

import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;
import durst.action.CalendarBasicAction;
import durst.data.Account;
import durst.data.Event;
import durst.data.Invite;
import durst.data.UserCalendar;
import durst.data.dao.DaoFactory;
import durst.data.dao.impl.AccountDao;
import durst.utils.BucketUtil;

public class EventEditActionBean extends CalendarBasicAction {
	@Validate(mask="\\w+")
	private String query;
	
	private FileBean file;

	@ValidateNestedProperties({
			@Validate(field = "id", required = true, maxlength = 15),
			@Validate(field = "title", required = true, maxlength = 15),
			@Validate(field = "description", required = true, maxlength = 300),
			@Validate(field = "repeated"), @Validate(field = "frequency"),
			@Validate(field = "startTime", required = true),
			@Validate(field = "endTime", required = true),
			@Validate(field = "doNotRepeatPast") })
	private Event event;
	
	@ValidationMethod(on = "edit")
	public void hasAccess(ValidationErrors errors) throws SQLException {
		DaoFactory.getInstance().createDao(UserCalendar.class).refresh(event.getParent());
		
		if (!event.getParent().getOwner().equals(context.getAccount()))
			errors.add(ValidationErrors.GLOBAL_ERROR, new SimpleError(
					"You don't have permissions to do that"));
	}
	

	@SuppressWarnings("unchecked")
	public Resolution edit() throws SQLException, IOException {
		DaoFactory.getInstance().createDao(Event.class).update(event);

		if (file != null) {
			file.save(BucketUtil.createFile(context.getAccount(), event, file.getFileName()));
		}

		if (query != null) {
			Account friend = ((AccountDao<Account, Integer>) DaoFactory.getInstance().createDao(
					Account.class)).queryByUsername(query);

			if (event.getParent().getOwner().equals(context.getAccount()) && friend != null) {
				for (Invite inv : event.getInvites())
					if (inv.getInvitee().equals(friend) && inv.getEvent().equals(event))
						return new RedirectResolution(ManageAccountActionBean.class);
				DaoFactory.getInstance().createDao(Invite.class).create(new Invite(friend, event, false));
			}
		}

		return new RedirectResolution(ManageAccountActionBean.class);
	}


	public String getQuery() {
		return query;
	}


	public void setQuery(String query) {
		this.query = query;
	}


	public FileBean getFile() {
		return file;
	}


	public void setFile(FileBean file) {
		this.file = file;
	}


	public Event getEvent() {
		return event;
	}


	public void setEvent(Event event) {
		this.event = event;
	}
}
